package com.tanhua.admin.listener;

import com.tanhua.api.MovementApi;
import com.tanhua.config.template.GreenTemplate;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AudiMessageListener {

    @Autowired
    private GreenTemplate greenTemplate;

    @DubboReference
    private MovementApi movementApi;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    name = "tanhua.movement.audi",
                    durable = "ture"
            ),
            exchange = @Exchange(
                    name = "tanhua.green.exchange",
                    type = ExchangeTypes.TOPIC
            ),
            key = "green.movement"
    ))
    public void audiMessage(String movementId) {
        //1 根据id查询动态数据
        Movement movement = movementApi.findById(movementId);

        try {
            //2 判断数据是否为空，  审核状态是否为0   保证操作的幂等性
            if (movement != null && movement.getState() == 0) {
                //3 执行审核
                Map<String, String> textScan = greenTemplate.greenTextScan(movement.getTextContent());
                Map<String, String> imageScan = greenTemplate.imageScan(movement.getMedias());

                String textSuggestion = textScan.get("suggestion");
                String imageSuggestion = imageScan.get("suggestion");

                //4 判断审核的结果，根据审核结果修改动态的审核状态
                if ("pass".equals(textSuggestion) && "pass".equals(imageSuggestion)) {
                    //审核通过
                    movementApi.updateState(movementId, 1);
                } else if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
                    //审核失败
                    movementApi.updateState(movementId, 2);
                } else {
                    //其他的情况，人工审核
                    movementApi.updateState(movementId, 3);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
